<?php

namespace Home\Controller;

require_once dirname(__FILE__) . '/../../../../vendor/workerman/gatewayclient/Gateway.php';
use Think\Controller;
use GatewayClient\Gateway;

include_once("Common.php");
include_once("mysqlha.php");

class DymanicController extends CommonController
{
    // 发布
    public function adddymanic()
    {
        $checkDymanic = M('config_system')->where(['title' => 'check_dymanic'])->getField('content');

        $data = I('post.', '', 'trim');

        foreach ($data as $key => $item) {
            $data[$key] = strip_tags($item);
        }

        if (isset($data['city'])) {
            $data['citys'] = $data['city'];
            unset($data['city']);
        }

        if (isset($data['privacy']) && $data['privacy']) {
            $data['source_type'] = 6;
            unset($data['privacy']);
        }

        $uid = $data['userid'];
        if (isset($data['source_type']) && $data['source_type'] == 6) {
            $uid = M('user')->where(['id'=>$uid])->getField('authcode');
        }
        $limit = M('user_deed_limit')->where(['user_id'=>$uid, 'type'=>1, 'update_time'=>0])->order('id desc')->find();
        if ($limit) {
            if ($limit['expire_time'] > time()) {
                exit(json_encode(['code' => 400, 'msg' => '当前已被限制发布内容']));
            }
        }

        $contain = M('filter_word')->where(['state' => 1])->getField('name', true);
        foreach ($contain as $k => $v) {
            if (stripos($data['content'], $v) !== false) {
                exit(json_encode(['code' => 400, 'msg' => '消息含有敏感词"' . $v . '",请重新编辑发送']));
            }
        }

        if (!isset($data['userid']) || !$data['userid']) {
            exit(json_encode(['code' => 400, 'msg' => '登录状态异常']));
        }
        $userInfo = M('user')->find($uid);
        if (!$userInfo) {
            exit(json_encode(['code' => 400, 'msg' => '登录状态异常']));
        }
        if ($userInfo['is_banned']) {
            exit(json_encode(['code' => 400, 'msg' => '当前仅支持提现']));
        }
        if ((!isset($data['content']) || !$data['content']) && (!isset($data['masterimg']) || !$data['masterimg'])) {
            exit(json_encode(['code' => 400, 'msg' => '内容不能为空']));
        }

        if ($checkDymanic + 0) {
            $data['shenhe'] = $checkDymanic ? 0 : 1;
            $msg = '发布成功，待审核通过';
        } else {
            $msg = '发布成功';
        }

        $data['visit'] = $data['xuni_thumbsup'] = rand(5,50);
        $data['thumbsup'] = 0;
        $data['comments'] = 0;
        $data['lover'] = 0;
        $data['lover'] = 0;
        $data['enroll'] = $data['video'] ? (getenv('APP_OSS_VIDEO_UPLOAD') ? 0 : 1) : 0;

        $data['liveness'] = $this->_calculateHotScoreNew($data['visit'],0,0,0,date('Y-m-d H:i:s'));


        // $limittime = strtotime('2023-04-15 00:00:00');
        // if (time() >= $limittime) {
        //     $user = M('user')->find($data['userid']);
        //     if (strtotime($user['register_datetime']) < $limittime) {
        //         exit(json_encode(['code' => 201, 'msg' => '发布失败']));
        //     }
        // }
       $sex=$data['sex'];//根据性别判断观看权限和评论权限  观看权限：男的看女的  女的看男的 评论权限：均可
		//dump($sex);die;
		if($sex=='男'){
		    $data['see_limit']=1;//女可看
		    $data['ping_limit']=3;//均可评
		}elseif($sex=='女'){
		    $data['see_limit']=2;//男可看
		    $data['ping_limit']=3;//均可评
		}else{
		    $data['see_limit']=0;//未开放
		    $data['ping_limit']=0;//未开放
		}
        $insetId = D('Dymanic')->data($data)->add();

        if ($insetId) {
            $type = $_REQUEST['type'] != 0 ? 6 : 2;
            if ($data['enroll']) {
                $redis = new \Redis();
                $redis->connect('127.0.0.1',getenv('REDIS_PORT'));
                if(getenv('REDIS_PASS')){
                    $redis->auth(getenv('REDIS_PASS'));
                }
                $redis->set(getenv('APP_NAME_EN').':rabbitMQReConsumption:' . $insetId,$insetId,10);
            }

            M('vip_num')->add(['user_id' => $data['userid'], 'type' => $type, 'date' => date("Y-m-d")]);

            $count = M('dymanic')->where(['userid' => $data['userid']])->count();

        if ($checkDymanic + 0) {
        } else {
            // 任务
            D('Task')->finish('dymanic_day', $data['userid'], $count);
        }

            exit(json_encode(['code' => 200, 'msg' => $msg]));
        }

        exit(json_encode(['code' => 201, 'msg' => '发布失败']));
    }
    public function _calculateHotScoreNew($viewCount, $replyCount, $likeCount, $shareCount, $time) {
        $viewWeightIndex = [0, 1, 31, 101, 501];
        $viewWeightValue = [10, 12, 15, 20, 25];

        $replyWeightIndex = [0, 1, 11, 31, 101];
        $replyWeightValue = [10, 12, 15, 20, 25];

        $likeWeightIndex = [0, 1, 11, 51, 201];
        $likeWeightValue = [10, 12, 15, 20, 25];

        $shareWeightIndex = [0, 1, 11, 31, 101];
        $shareWeightValue = [10, 12, 15, 20, 25];

        $viewWeight = 0;
        for ($i=sizeof($viewWeightIndex) - 1; $i >= 0; $i--) {
            if ($viewWeightIndex[$i] <= $viewCount) {
                $viewWeight = $viewWeightValue[$i];
                break;
            }
        }
        
        $replyWeight = 0;
        for ($i=sizeof($replyWeightIndex) - 1; $i >= 0; $i--) {
            if ($replyWeightIndex[$i] <= $replyCount) {
                $replyWeight = $replyWeightValue[$i];
                break;
            }
        }
        
        $likeWeight = 0;
        for ($i=sizeof($likeWeightIndex) - 1; $i >= 0; $i--) {
            if ($likeWeightIndex[$i] <= $likeCount) {
                $likeWeight = $likeWeightValue[$i];
                break;
            }
        }
        
        $shareWeight = 0;
        for ($i=sizeof($shareWeightIndex) - 1; $i >= 0; $i--) {
            if ($shareWeightIndex[$i] <= $shareCount) {
                $shareWeight = $shareWeightValue[$i];
                break;
            }
        }

        $timenow = time();

        $timeWeightIndex = [1, 2, 8, 31, 91];
        $timeWeightValue = [30, 20, 15, 12, 10];
        $timeWeight = 0;
        for ($i=sizeof($timeWeightIndex) - 1; $i >= 0; $i--) {
            if ($timeWeightIndex[$i] <= ceil(($timenow - strtotime($time)) / 86400)) {
                $timeWeight = $timeWeightValue[$i];
                break;
            }
        }

        $hotScore = $viewWeight + $replyWeight + $likeWeight + $shareWeight + $timeWeight;
        return $hotScore;
    }

    // 分类
    public function category()
    {
        $page = I('page') ? I('page') * 10 : 0;

        $data = M('dymanic_category')
            ->field('id, name, image')
            ->where(['is_hide' => 0])->order('des asc, id desc')
            ->limit($page, 10)->select();

        exit(json_encode(['code' => 200, 'result' => $data]));

    }

    //系统广播列表
    public function sysdymanic()
    {
        $model = M();

        $sql = "select dy_id,content,citys,fabu_city,datetime,sumbImage,masterimg,lover,thumbsup,addtime,enroll,comments from dymanic where type=2 ORDER BY top DESC, dy_id desc;";
        $data = $model->query($sql);

        foreach ($data as $key => $item) {
            $data[$key]['num'] = 0;
            $data[$key]['distance'] = format_distance($item['distance']);
            $data[$key]['masterimg'] = explode(",", $item['masterimg']);
            $data[$key]['sumbImage'] = explode(",", $item['sumbImage']);
            $data[$key]['vip_end_datetime'] = strtotime($item['vip_end_datetime']) >= time() ? 1 : 0;
            $data[$key]['through_membership'] = explode(" ", $item['through_membership'])[1];
            $data[$key]['id'] = null;
            $data[$key]['head_100'] = "/public/style/index/img/logo.png";
            $data[$key]['head_300'] = "/public/style/index/img/logo.png";
            $data[$key]['name'] = "系统";
            $data[$key]['age'] = "保密";
            $data[$key]['sex'] = "保密";
            $data[$key]['attestation'] = "1";
            $data[$key]['overdue'] = "0";
            $data[$key]['is_vip'] = "1";
            $data[$key]['islover'] = 0;
            $data[$key]['isthumbsup'] = 0;
            $data[$key]['enroll'] = 0;
        }

        exit(json_encode(['code' => 200, 'result' => $data]));
    }

    // 动态列表 (弃)
    public function dymaniclst()
    {
        $page = I('page') ?: 0;             // 当前页
        $pagecount = I('count') ?: 9;       // 每页数量
        $userid = I('userid');              // 用户ID
        $username = I('username');          // keyword(用户搜索)
        $citys = I('citys');                // keyword(城市搜索)
        $sex = I('sex') ?: 0;               // 性别筛选 0不限|1女性|2男性
        $longitude = I('longitude');        // 经度
        $latitude = I('latitude');          // 纬度
        $new = I('new');                    // 排序(最新发布)
        $recently = I('recently');          // 排序(最近约会)
        $type = I('type') ?: 3;             // 此参数判定在系统消息-电台广播 显示动态列表，那里根据userid用户offten_city筛选出动态约会城市的广播
        $category_id = I('category_id');    // 分类ID
        $following = I('following');        // 关注的人
        $chosen = I('chosen');              // 精选
        $sort = I('sort');                  // 排序
        $slide = I('slide');                // 轮播
        $nav = I('nav') ?: 1;               // 1默认 | 2关注 | 3同城
        $uid = I('uid');                    // 用户ID筛选

        $startcount = $page * $pagecount;

        $model = M();

        $where = "dy.shenhe = 1 and u.id = dy.userid and dy.type = $type";

        $order = "dy.addtime desc";

        if ($nav == 1) {
            /*$expire = date('Y-m-d H:i:s', strtotime('-3 month'));
            $where .= " and dy.addtime > '$expire'";*/

            $user = M('user')->where(['id' => $userid])->find();

            $sex = $user['sex'] == '男' ? '女' : '男';

            $where .= " and u.sex = '$sex' and (u.age between " . ($user['age'] - 5) . " and " . ($user['age'] + 5) . ")";
        } else if ($nav == 2) {
            $ids = M('attention')->where(['user_id' => $userid, 'sys_channel' => 1])->getField('to_user', true);

            $ids = $ids ? '(' . implode(',', $ids) . ')' : '(0)';
            $where .= ' and userid in' . $ids;
        } else if ($nav == 3) {
            $my_city = M('user')->where(['id' => $userid])->getField('city');

            if ($my_city) {
                $where .= " and dy.citys like '%" . $my_city . "%'";
            }
        }

        if ($uid) {
            $where .= " and dy.userid = $uid";
        } else {
            // 黑名单过滤
            $blacklist = M("blacklist")->where('user_id=' . $userid)->getField('to_user', true);
            if ($blacklist) {
                $blacklist[] = $userid;

                $uids = implode(',', $blacklist);

                $where .= " and dy.userid not in (" . $uids . ")";
            } else {
                $where .= " and dy.userid <> $userid";
            }
        }


        // 用户搜索
        if ($username) {
            $where .= " and u.name = '" . $username . "' ";
        }

        if ($category_id) {
            $where .= " and dy.category_id = " . $category_id;
        }


        $whereOr = $where;

        if ($slide) {
            $where .= " and type = 1 and masterimg <> ''";
            $order = 'sort desc, visit desc, ' . $order;

            $whereOr = $where;
        }

        if (in_array($nav, [1,3]) && !$uid) {
            $order = 'rand()';

            if ($nav == 1) {
                $where2 = $where;

                $where .= " and dy.citys like '%" . $user['city'] . "%'";
                $where2 .= " and dy.citys not like '%" . $user['city'] . "%'";
            }
        } else {
            $order = 'dy.dy_id desc';
        }

        $field = "dy.*,u.id,u.head_100,u.head_300,u.nvshen,u.kejian,u.through_membership,u.name,u.age,u.sex,
            u.is_identity_authentication,u.attestation,u.constellation, u.noble_grade, u.noble_time,u.xuni_discount, 
            u.hide_distance, u.register_datetime, u.realname_auth, u.stature, u.occupation";

        if ($nav == 1) {
            $sql = "(select $field from dymanic as dy, user as u where $where ORDER BY $order limit $pagecount) 
                    union
                    (select $field from dymanic as dy, user as u where $where2 ORDER BY $order limit $pagecount) 
                    limit $startcount,$pagecount;";

        } else {
            $sql = "select $field from dymanic as dy, user as u where ($where) or ($whereOr) ORDER BY $order limit $startcount,$pagecount;";
        }

        $data = $model->query($sql);

        if ($data) {
            $start = strtotime(date("Ymd"));

            $thumbsups = M('dymanic_userthumbsup')->where(['userid' => $userid])->getField('dy_id', true);
            $loves = M('dymanic_userlover')->where(['userid' => $userid])->getField('dy_id', true);
            $category = M('dymanic_category')->where(['id' => ['gt', 0]])->getField('id, name');
            $gradeNoble = M('grade_noble')->where(['id' => ['gt', 0]])->getField('grade, icon');
            $attentions = M('attention')->where(['user_id' => $userid, 'sys_channel' => 1])->getField('to_user', true);


            if ($type == 1) {
                $ids = array_column($data, 'to_user');

                $users = M('user')->where(['id' => ['in', $ids]])->getField('id, name, head_100 avatar');
            }

            $ids = array_column($data, 'userid');
            $personals = M('config_personal')->where(['user_id' => ['in', $ids]])->getField('user_id, id, hide_distance');

            $config = M('config_system')->where(['category' => 'user'])->getField('title, content');

            foreach ($data as $key => $item) {
                if (isset($personals[$item['userid']]['hide_distance']) && $personals[$item['userid']]['hide_distance']) {
                    $data[$key]['citys'] = '';
                }
                $data[$key]['is_new'] = (strtotime($item['register_datetime']) + 86400) > time() ? 1 : 0;
                $data[$key]['overdue'] = $start > strtotime($item['addtime']) ? 1 : 0;
                $data[$key]['isthumbsup'] = in_array($item['dy_id'], $thumbsups) ? 1 : 0;
                $data[$key]['islover'] = in_array($item['dy_id'], $loves) ? 1 : 0;
                $data[$key]['is_following'] = in_array($item['userid'], $attentions) ? 1 : 0;
                $data[$key]['num'] = $item['thumbsup'];

                $distance = $item['xuni_discount'] + 0 ? $item['xuni_discount'] : $item['distance'];
                $data[$key]['distance'] = $item['hide_distance'] ? '保密' : ($distance >= 1000 ? number_format(($distance / 1000), 1) . 'km' : number_format($distance, 1) . 'm');

                if ($config['hide_city'] && $item['sex'] == '女') {
                    $data[$key]['citys'] = '';
                }

                $data[$key]['masterimg'] = explode(",", $item['masterimg']);
                $data[$key]['sumbImage'] = explode(",", $item['sumbImage']);
                $data[$key]['through_membership'] = explode(" ", $item['through_membership'])[1];

                if ($type == 1) {
                    $data[$key]['another_name'] = $users[$item['to_user']]['name'] ?? '';
                    $data[$key]['another_avatar'] = $users[$item['to_user']]['avatar'] ?? '';

                    if ($slide) {
                        $data[$key]['slide_cover'] = $data[$key]['sumbImage'][0];
                        $data[$key]['slide_cate'] = $category[$item['category_id']] ?? '';

                    }
                } else {
                    $data[$key]['another_name'] = '';
                    $data[$key]['another_avatar'] = '';
                }

                if ($item['noble_grade'] && $item['noble_time'] > time()) {
                    $data[$key]['noble_icon'] = isset($gradeNoble[$item['noble_grade']]) ? changeUrl($gradeNoble[$item['noble_grade']]) : '';

                    $data[$key]['is_vip'] = 1;
                } else {
                    $data[$key]['is_vip'] = 0;
                }

                $data[$key]['video'] = changeUrl($item['video']);
                $data[$key]['cover'] = changeUrl($item['cover']);
            }
        } else {
            $data = [];
        }

        exit(json_encode(['code' => 200, 'result' => $data]));
    }

    //详细动态+评论+回复
    public function dycommentlsts()
    {
        $dy_id = $_REQUEST['dy_id'];
        $userid_privacy = $userid = $_REQUEST['userid'];

        $model = M();




        //查询动态
        $sql = "SELECT m.dy_id,m.category_id,m.userid,m.to_user, m.content,m.addtime,m.citys,m.lover,m.xuni_thumbsup,m.thumbsup num,
            m.between,m.addtime,m.sumbImage,m.masterimg,m.datetime,m.voice,m.video,m.cover,m.visit,u.vip_end_datetime,u.name,u.head_100,
            u.head_300,u.sex,u.age,u.constellation,u.through_membership,u.is_identity_authentication,u.attestation,u.realname_auth,
            u.noble_grade,u.noble_time,u.register_datetime, u.stature, u.occupation,m.class,m.title,m.topic,m.price,u.auth_tag,m.topic_experience,m.source_type,u.reg,m.ping_limit FROM dymanic m,user u where u.id=m.userid AND dy_id=$dy_id and u.delete_time = 0";
        $data = $model->query($sql)[0];

        if ($data['reg'] == 2) {
            $userid_privacy = M('user')->where(['authcode'=>$userid, 'reg'=>2])->getField('id');
        }

        if (!$data['ping_limit']) {
            $data['ping_limit'] = false;
        } else if ($data['ping_limit'] != 3) {
            $userinfo = M('user')->find($userid_privacy);
            $limitsex = ['','女','男'];
            $data['ping_limit'] = $limitsex[$data['ping_limit']] == $userinfo['sex'];
        } else {
            $data['ping_limit'] = true;
        }

        $update['visit'] = $data['visit'] + 1;
        $update['liveness'] = $this->_calculateHotScoreNew($update['visit'],$data['comments'],$data['thumbsup'],$data['shares'],$data['addtime']);
        M('dymanic')->where(['dy_id' => $dy_id])->save($update);

        M('user')->where(['id' => $data['userid']])->setInc('charm_value', 0.01);

        //查询是否点赞
        $thumbsup = $model->query("select dy_id from dymanic_userthumbsup where userid=$userid_privacy and dy_id=$dy_id");

        $lover = $model->query("select dy_id from dymanic_userlover where userid=$userid_privacy and dy_id=$dy_id");

        $hasRead = M('dymanic_read')->where(['dy_id'=>$dy_id, 'userid'=>$userid])->find();
        if ($hasRead) {
            M('dymanic_read')->where(['id'=>$hasRead['id']])->save(['time'=>date('Y-m-d H:i:s')]);
        } else {
            M('dymanic_read')->add(['dy_id'=>$dy_id, 'userid'=>$userid]);
        }

        $config = M('config_system')->where(['category' => 'user'])->getField('title, content');
        $personals = M('config_personal')->where(['user_id' => $data['userid']])->getField('user_id, id, hide_distance');

        if (isset($personals[$data['userid']]['hide_distance']) && $personals[$data['userid']]['hide_distance']) {
            $data['citys'] = '';
        }

        if ($config['hide_city'] && $data['sex'] == '女') {
            $data['citys'] = '';
        }

        $data['is_new'] = (strtotime($data['register_datetime']) + 86400) > time() ? 1 : 0;
        $data['isthumbsup'] = $thumbsup ? 1 : 0;
        $data['islover'] = $lover ? 1 : 0;

        $data['masterimg'] = explode(",", $data['masterimg']);

        $data['sumbImage'] = explode(",", $data['sumbImage']);

        $data['vip_end_datetime'] = strtotime($data['vip_end_datetime']) >= time() ? 1 : 0;
        $data['num'] += $data['xuni_thumbsup'];


        $data['price'] *= getenv('APP_RATE');
        $data['paystate'] = 1;
        if ($data['class'] == 2 && $data['userid'] != $userid) {
            $data['paystate'] = M('order_of_subscribe')->where(['user_id'=>$userid, 'dy_id'=>$dy_id])->count();
        }

        if ($data['topic']) {
            $topic = array_filter(explode('#',$data['topic']));
            $data['topic'] = [];
            foreach ($topic as &$v) {
                if ($v) $data['topic'][] = $v;
            }
        } else {
            $data['topic'] = [];
        }

        if ($data['topic_experience']) {
            $topic_experience = array_filter(explode('&',$data['topic_experience']));
            $data['topic_experience'] = [];
            foreach ($topic_experience as &$v) {
                if ($v) $data['topic_experience'][] = $v;
            }
        } else {
            $data['topic_experience'] = [];
        }

        if ($data['class'] == 2) {
            $data['tips'] = '<div style="font-weight:bold;font-size:15px;padding:20px;background:#f6f6f6;"><p style="font-weight:400;margin-bottom:6px;">温馨提示：</p>去认证经验和擅长，就可以发布付费作品和付费的服务，以及作品能得到更多的流量</div>';
        }

        unset($data['xuni_thumbsup']);

        //点赞人列表
        $zan = [];

        $zan = M('dymanic_userthumbsup')->alias("dy")
            ->join("LEFT JOIN user as u on dy.userid=u.id")//左链接
            ->field("u.id,u.name,u.head_portrait,u.head_300,u.head_100")//左表显示全部字段，右表显示部分字段
            ->where("dy.dy_id=" . $data['dy_id'])//条件
            ->order('dy.id desc')
            ->select();

        $data['zan'] = $zan ?: [];

        //$num = M('dymanic_userthumbsup')->where(['dy_id' => $data['dy_id']])->count('userid');

        //$data['num'] = $num ?: 0;


        //评论列表
        $text = [];

        $text = M('dycomment')->alias("dy")
            ->join("LEFT JOIN user as u on dy.userid=u.id")
            ->field("dy.comment_id,dy.content,dy.addtime, u.id,u.name,u.head_portrait,u.head_300,u.head_100")
            ->where("dy.dy_id=" . $data['dy_id'] . " and dy.shenhe=1")
            ->order('dy.addtime desc')
            ->select();

        $data['text'] = $text ?: [];


        $gradeNoble = M('grade_noble')->where(['id' => ['gt', 0]])->getField('id, icon');

        $data['noble_icon'] = $gradeNoble[$data['noble_icon']] ?? '';


        $data['to_user_name'] = '';
        $data['to_user_avatar'] = '';
        if ($data['to_user']) {
            $toUser = M('user')->where(['id' => $data['to_user']])->find();

            if ($toUser) {
                $data['to_user_name'] = $toUser['name'];
                $data['to_user_avatar'] = changeUrl($toUser['head_100']);
            }
        }


        $attention = M('attention')->where(['user_id' => $userid, 'to_user' => $data['userid'], 'sys_channel' => 1])->find();
        $data['is_attention'] = $attention ? 1 : 0;


        $this->ajaxReturn(['code' => 200, 'result' => $data]);
    }

    //评论动态+回复评论
    public function comment()
    {
        // $this->ajaxReturn(['code' => 400, 'msg' => '暂未开放评论区']);

        $checkDymanic = M('config_system')->where(['title' => 'check_dycomment'])->getField('content');

        $dy_id = $_REQUEST['dy_id'];//动态id
        $content = $_REQUEST['content'];//评论内容
        $userid = $_REQUEST['userid'];//评论者id\
        $touserid = $_REQUEST['touserid'];//给他回复，他的id
        $type = $_REQUEST['type'];//0为评论，1为回复
        $user = M('user')->where(['id'=>$userid])->find();
        if (!$user) {
            exit(json_encode(['code' => 400, 'msg' => '登录失效']));
        }
        if (strtotime($user['banned_end_time']) > time()) {
            exit(json_encode(['code' => 400, 'msg' => '账号封禁状态不可评论']));
        }
        if ($user['reg'] == 2) {
            $user_real = M('user')->where(['id'=>$user['authcode']])->find();
            if (!$user_real) {
                exit(json_encode(['code' => 400, 'msg' => '登录失效']));
            }
            if (strtotime($user_real['banned_end_time']) > time()) {
                exit(json_encode(['code' => 400, 'msg' => '账号封禁状态不可评论']));
            }
        }
        $dymanic = M('dymanic')->where(['dy_id'=>$dy_id, 'shenhe'=>1])->find();
        if (!$dymanic) {
            exit(json_encode(['code' => 400, 'msg' => '内容不见了']));
        }

        if (!in_array($dymanic['ping_limit'], $user['sex'] == '男'?[2,3]:[1,3])) exit(json_encode(['code' => 400, 'msg' => '当前未开放评论']));

        $uid = $userid;
        $limit = M('user_deed_limit')->where(['user_id'=>$uid, 'type'=>2, 'update_time'=>0])->order('id desc')->find();
        if ($limit) {
            if ($limit['expire_time'] > time()) {
                exit(json_encode(['code' => 400, 'msg' => '当前已被限制发布评论']));
            }
        }

        if ($dymanic['source_type'] == 6) {
            if ($user['reg'] != 3) {
                $user = M('user')->where(['reg'=>2, 'authcode'=>$user['id']])->find();
                IF (!$user) {
                    exit(json_encode(['code' => 400, 'msg' => '未创建匿名电报账号']));
                }
                $userid = $user['id'];
            }
        }
        $content = strip_tags($content);
        if(ishasPhoneNumber($content)){
            exit(json_encode(['code' => 400, 'msg' => '禁止发送手机号']));
        }

        $contain = M('filter_word')->where(['state' => 1])->getField('name', true);
        foreach ($contain as $k => $v) {
            if (stripos($content, $v) !== false) {
                exit(json_encode(['code' => 400, 'msg' => '消息含有敏感词"' . $v . '",请重新编辑发送']));
            }
        }

        $insertArr = array(
            "dy_id" => $dy_id,
            "content" => $content,
            "userid" => $userid,
            "touserid" => $touserid,
            "type" => $type,
            "shenhe" => $checkDymanic == 0 ? 1 : 0
        );

        // myinsert('dycomment', $insertArr);
        $res = M('dycomment')->add($insertArr);




        if ($checkDymanic + 0) {
            $data['shenhe'] = $checkDymanic ? 0 : 1;
            $msg = '评论成功，待审核通过';
        } else {
            if (!$type) {
                // 动态评论数+1
                M('dymanic')->where(['dy_id' => $dy_id])->setInc('comments');
                M('user')->where(['id' => $dymanic['userid']])->setInc('charm_value', 2);
            }
            $msg = '评论成功';

            if ($touserid && $touserid != $userid && $dymanic['state'] == 0 && ($dymanic['addway']==2 || ($dymanic['addway']==0&&$dymanic['userid']!=$touserid))) {
                $member = M('user')->where(['id' => $userid])->find();
                $message = [
                    'type' => 17,
                    'to_user' => $touserid,
                    'context' => json_encode([
                                    'name' => $member['name'],
                                    'head' => $member['head_100'],
                                    'content' => $content,
                                    'dy_id' => $dy_id,
                                    'comment_id' => $res
                                ], JSON_UNESCAPED_UNICODE),
                    'uid' => $member['id'],
                    'user_id' => $res //评论id
                ];

                M('sys_message')->add($message);


                $Gatewaymessage = json_encode([
                    "code" => 200,
                    "action" => 'api/Privatechat/interactionCount',
                    'data' => []
                ]);

                Gateway::sendToUid(getenv('SOCKET_PREFIX') . $touserid, $Gatewaymessage);
            }

        }


        if ($user['reg'] == 1) {
            $count = M('dycomment')->where(['userid' => $userid])->count();
            // 任务
            D('Task')->finish('dymanic_comment', $userid, $count);
        }

        // 推送
        /*$datas = json_encode(['type' => 5, 'userid' => $userid, 'name' => $name, 'dy_id' => $dy_id], JSON_UNESCAPED_UNICODE);
        D('Push')->send(5, $touserid, '消息提醒', "{$name} 评论了你发布的动态", $datas);*/

        $returnarr = [
            "code" => 200,
            "msg" => $msg
        ];
        
        D('UserActiveval')->inc($userid, 'dynamic_comment');

        echo json_encode($returnarr);
    }

    //点赞thumbsup
    public function thumbsup()
    {
        $model = M();
        $type = $_REQUEST['type'];//1为点赞，2为取消点赞
        $userid = $_REQUEST['userid'];
        $dy_id = $_REQUEST['dy_id'];
        $dymanic = M('dymanic')->where(['dy_id'=>$dy_id])->find();
        switch ($type) {
            case 1:
                $thumbsup = M('dymanic_userthumbsup')->where(['dy_id' => $dy_id, 'userid' => $userid])->select();

                if ($thumbsup) {
                    $result = array("code" => 201, "msg" => "点赞失败,已点赞，无需重复操作");
                    $this->ajaxReturn($result);
                }

                $code = $model->execute("UPDATE dymanic SET `thumbsup`=`thumbsup`+1 WHERE dy_id=$dy_id;");

                $model->execute("insert into dymanic_userthumbsup (userid,dy_id) values ($userid,$dy_id);");

                if ($code !== false) {
                    D('UserActiveval')->inc($userid, 'dynamic_thumb');
                    $result = array("code" => 200, "msg" => "点赞成功");


                    M('user')->where(['id' => $dymanic['userid']])->setInc('charm_value', 1);

                    /*$user_id = M('dymanic')->where(['dy_id' => $dy_id])->getField('userid');

                    $name = M('user')->where(['id' => $userid])->getField('name');

                    $arr = [
                        'to_user' => $user_id,
                        'uid' => $userid,
                        'user_id' => $dy_id,//存动态ID
                        'context' => json_encode([
                            'name' => $name,
                            'desc' => "{$name} 给你的动态点了赞"
                        ]),
                        'type' => 12
                    ];

                    M('sys_message')->data($arr)->add();*/

                    // 推送
                    /*$datas = json_encode(['type' => 4, 'userid' => $user_id, 'name' => $name, 'dy_id' => $dy_id], JSON_UNESCAPED_UNICODE);
                    D('Push')->send(4, $userid, '消息提醒', "{$name} 给你的动态点了赞", $datas);*/

                } else {
                    $result = array("code" => 201, "msg" => "点赞失败");
                }
                break;
            case 2:
                $thumbsup = M('dymanic_userthumbsup')->where(['dy_id' => $dy_id, 'userid' => $userid])->select();

                if (!$thumbsup) {

                    $result = array("code" => 201, "msg" => "取消点赞失败,无点赞记录");

                    $this->ajaxReturn($result);

                }

                $code = $model->execute("UPDATE dymanic SET `thumbsup`=`thumbsup`-1 WHERE dy_id=$dy_id;");

                $model->execute("delete from dymanic_userthumbsup where userid=$userid and dy_id=$dy_id");

                if ($code !== false) {

                    $result = array("code" => 200, "msg" => "取消点赞成功");
                    M('user')->where(['id' => $dymanic['userid']])->setDec('charm_value', 1);

                } else {

                    $result = array("code" => 201, "msg" => "取消点赞失败");

                }
            default:

                break;
        }

        $this->ajaxReturn($result);
    }

    //点喜欢lover
    public function lover()
    {
        $model = M();

        $type = $_REQUEST['type'];//1为点喜欢，2为取消喜欢

        $userid = $_REQUEST['userid'];

        $dy_id = $_REQUEST['dy_id'];
        $dymanic = M('dymanic')->where(['dy_id'=>$dy_id])->find();
        switch ($type) {

            case 1:

                $code = $model->execute("UPDATE dymanic SET `lover`=`lover`+1 WHERE dy_id=$dy_id;");

                $model->execute("insert into dymanic_userlover (userid,dy_id) values ($userid,$dy_id);");

                if ($code !== false) {

                    $result = array("code" => 200, "msg" => "喜欢成功");

                    M('user')->where(['id' => $dymanic['userid']])->setInc('charm_value', 5);

                } else {

                    $result = array("code" => 201, "msg" => "喜欢失败");

                }

                break;


            case 2:

                $code = $model->execute("UPDATE dymanic SET `lover`=`lover`-1 WHERE dy_id=$dy_id;");

                $model->execute("delete from dymanic_userlover where userid=$userid and dy_id=$dy_id");

                if ($code !== false) {

                    $result = array("code" => 200, "msg" => "取消喜欢成功");

                    M('user')->where(['id' => $dymanic['userid']])->setDec('charm_value', 5);

                } else {

                    $result = array("code" => 201, "msg" => "取消喜欢失败");

                }

            default:

                break;

        }

        $this->ajaxReturn($result);

    }

    //动态列表约会报名
    public function enroll()
    {
        $dy_id = I('dy_id');      //动态ID
        $user_id = I('user_id');  //报名用户ID

        //报名人性别
        $sex1 = M('user')->where('id=' . $user_id)->getField('sex');

        //发布动态人性别
        $id = M('dymanic')->where('dy_id=' . $dy_id)->getField('userid');
        $sex2 = M('user')->where('id=' . $id)->getField('sex');

        if ($sex1 == $sex2) {
            $result = ['code' => 220, 'msg' => '同性报名限制'];
            $this->ajaxReturn($result);
        }

        if ($sex1 == '男') {
            $vip = M('user')->where('id=' . $user_id)->getField('vip_end_datetime');
            if ($vip <= date('Y-m-d H:i:s')) {
                $result = ['code' => 220, 'msg' => '开通会员后才能报名'];
                $this->ajaxReturn($result);
            }
        }

        $dy = M('dymanic')->where(['dy_id' => $dy_id])->find();
        if (!$dy) {
            $result = ['code' => 220, 'msg' => '动态不存在'];
            $this->ajaxReturn($result);
        }

        $enroll = M('dymanic_enroll')->where(['dy_id' => $dy_id, 'user_id' => $user_id])->find();

        if ($enroll) {
            $result = ['code' => 220, 'msg' => '无需重复报名'];
            $this->ajaxReturn($result);
        } else {
            $num = M('dymanic')->where('dy_id=' . $dy_id)->getField('enroll');
            $num = $num + 1;

            //dymanic表报名人数字段+1
            $res = M('dymanic')->where('dy_id=' . $dy_id)->setField('enroll', $num);

            if ($res) {
                $data = [
                    'dy_id' => $dy_id,
                    'user_id' => $user_id,
                    'main_id' => $id
                ];

                if (M('dymanic_enroll')->data($data)->add()) {

                    $uid = M('dymanic')->where(['dy_id' => $dy_id])->getField('userid');

                    $name = M('user')->where(['id' => $user_id])->getField('name');

                    $context = ['name' => $name, 'desc' => $name . "报名了你发布的广播"];

                    $arr = [
                        'to_user' => $uid,
                        'uid' => $user_id,
                        'user_id' => $dy_id,//存动态ID
                        'context' => json_encode($context),
                        'type' => 13
                    ];
                    M('sys_message')->data($arr)->add();

                    // 推送
                    /*$datas = json_encode(['type' => 3, 'userid' => $user_id, 'name' => $name, 'dy_id' => $dy_id], JSON_UNESCAPED_UNICODE);
                    D('Push')->send(3, $uid, '消息提醒', "{$name} 报名了你发布的动态", $datas);*/

                    $result = ['code' => 200, 'data' => $data, 'msg' => '报名成功'];
                    $this->ajaxReturn($result);

                } else {
                    $num = M('dymanic')->where('dy_id=' . $dy_id)->getField('enroll');

                    $num = $num - 1;

                    //dymanic表报名人数字段-1
                    M('dymanic')->where('dy_id=' . $dy_id)->setField('enroll', $num);

                    $result = ['code' => 220, 'msg' => '报名失败'];
                    $this->ajaxReturn($result);
                }
            } else {
                $result = ['code' => 220, 'msg' => '报名失败'];
                $this->ajaxReturn($result);
            }
        }
    }

    //动态列表约会报名取消
    public function cancelenroll()

    {

        $user_id = $_REQUEST['user_id'];  //报名用户ID

        $dy_id = $_REQUEST['dy_id'];      //动态ID


        $dy = M('dymanic')->where(['dy_id' => $dy_id])->find();

        if (!$dy) {

            $result = ['code' => 220, 'msg' => '动态不存在'];

            $this->ajaxReturn($result);

        }


        $enroll = M('dymanic_enroll')->where(['dy_id' => $dy_id, 'user_id' => $user_id])->find();


        if ($enroll) {

            $num = M('dymanic')->where('dy_id=' . $dy_id)->getField('enroll');

            $num = $num - 1;


            /*  //dymanic表报名人数字段-1

                $res = M('dymanic')-> where('dy_id='.$dy_id)->setField('enroll',$num);



                if($res){

                    $data = [

                        'dy_id' => $dy_id,

                        'user_id' => $user_id

                    ];



                    if(M('dymanic_enroll')->where(['user_id'=>$user_id,'dy_id'=>$dy_id])->delete()){

                        $result = ['code' => 200,'data'=>$data,'msg' =>'取消报名成功'];

                        $this->ajaxReturn($result);

                    }else{

                        $num = M('dymanic')->where('dy_id='.$dy_id)->getField('enroll');

                        $num = $num + 1;



                        //dymanic表报名人数字段+1

                        $res = M('dymanic')-> where('dy_id='.$dy_id)->setField('enroll',$num);



                        $result = ['code' => 220,'msg' =>'取消报名失败'];

                        $this->ajaxReturn($result);

                    }

                }*/


            // 启动事务

            M()->startTrans();


            // 准备数据

            $res1 = M('dymanic')->where('dy_id=' . $dy_id)->setField('enroll', $num);

            $res2 = M('dymanic_enroll')->where(['user_id' => $user_id, 'dy_id' => $dy_id])->delete();


            if ($res1 !== false && $res2 !== false) {

                M()->commit();


                $data = [

                    'dy_id' => $dy_id,

                    'user_id' => $user_id

                ];

                $result = ['code' => 200, 'data' => $data, 'msg' => '取消报名成功'];

                $this->ajaxReturn($result);

            } else {

                M()->rollback();


                $result = ['code' => 220, 'msg' => '取消报名失败'];

                $this->ajaxReturn($result);

            }

        } else {

            $result = ['code' => 220, 'msg' => '取消报名失败'];

            $this->ajaxReturn($result);

        }

    }

    //动态报名列表
    public function enrolllist()
    {
        $dy_id = $_REQUEST['dy_id'];      //动态ID

        $dymanic = M('dymanic')->where(['dy_id' => $dy_id])->select();

        if (!$dymanic) {
            $this->ajaxReturn(['code' => 220, 'msg' => '动态不存在']);
        }

        $user_list = M('dymanic_enroll')->where(['dy_id' => $dy_id])->order('bm_time desc')->getfield('user_id', true);
        $bmtime_list = M('dymanic_enroll')->where(['dy_id' => $dy_id])->order('bm_time desc')->getfield('bm_time', true);


        if (!$user_list) {
            $this->ajaxReturn(['code' => 220, 'msg' => '动态暂无人报名']);
        }

        $data = [];

        foreach ($user_list as $k => $v) {
            $item = '';

            $user = M('user')->where(['id' => $v])->select()[0];

            $img_count = M('user_img')->where("user_id=" . $v->id)->count();

            if (time() < strtotime($user['vip_end_datetime'])) {
                $user['is_vip'] = time() < strtotime($user['vip_end_datetime']) ? 1 : 0;
            }


            //上次登录时间

            $time = strtotime($user['last_login_datetime']);
            if (!$time) {
                $time = "未知";
            }

            $diff = time() - $time;

            if ($diff < 5) {
                $time = "在线";
            } else if ($diff < 60) {
                $time = "刚刚";
            } else if ($diff < 3600) {
                $time = floor($diff / 60) . "分钟前";
            } else if ($diff < 86400) {
                $time = floor($diff / 3600) . "小时前";
            } else if ($diff < (86400 * 7)) {
                $time = floor($diff / 86400) . "天前";
            } else if ($diff < (86400 * 30)) {
                $time = floor($diff / 86400 / 7) . "周前";
            } else if ($diff < (86400 * 366)) {
                $time = floor($diff / 86400 / 30) . "个月前";
            } else if ($diff < (86400 * 366 * 3)) {
                $time = floor($diff / 86400 / 365) . "年前";
            } else {
                $time = date("Y-m-d H:i:s", $time);
            }

            $item = [
                "user_id" => $user['id'],
                "user_head" => $user['head_300'],
                "user_name" => $user['name'],
                "city" => $user['city'],
                "occupation" => $user['occupation'],
                "user_distance" => format_distance($user['distance']),//距离
                "user_sex" => $user['sex'],
                "user_age" => $user['age'],
                "imgcount" => $img_count[0] ? $img_count[0] : 0,
                "is_vip" => $user['is_vip'],
                "attestation" => $user['attestation'],
                "last_login_datetime" => $time,
                'bm_time' => $bmtime_list[$k]
            ];

            $data[] = $item;
        }

        $this->ajaxReturn(['code' => 200, 'data' => $data, 'msg' => '操作成功']);
    }

    //选择约会
    public function tryst()
    {

        $user_id = $_REQUEST['user_id'];  //约会用户ID

        $dy_id = $_REQUEST['dy_id'];      //动态ID


        $dy = M('dymanic')->where(['dy_id' => $dy_id])->find();

        if (!$dy) {

            $result = ['code' => 220, 'msg' => '动态不存在'];

            $this->ajaxReturn($result);

        }


        $enroll = M('dymanic_enroll')->where(['dy_id' => $dy_id, 'user_id' => $user_id])->find();

        if (!$enroll) {

            $result = ['code' => 220, 'msg' => '此用户未报名'];

            $this->ajaxReturn($result);

        }


        $tryst = M('dymanic_enroll')->where(['dy_id' => $dy_id, 'user_id' => $user_id])->getfield('tryst');


        if ($tryst) {

            $result = ['code' => 220, 'msg' => '约会已选择,无需重复操作'];

            $this->ajaxReturn($result);

        } else {

            $res = M('dymanic_enroll')->where(['dy_id' => $dy_id, 'user_id' => $user_id])->setField('tryst', 1);


            if ($res) {

                $result = ['code' => 200, 'msg' => '约会选择成功'];

                $this->ajaxReturn($result);

            }

        }

    }

    //检查是否有评价权限
    public function checkeva()
    {
        $user_id = $_REQUEST['user_id'];  //评价用户ID
        $to_user = $_REQUEST['main_id'];  //被评价用户ID

        $user = M('user')->where(['id' => $user_id])->find();
        if ($user['sex'] == '男') {
            $pingjia1 = M('vip_num')->where(['user_id' => $user_id, 'to_user' => $to_user, 'type' => 1])->select();
        } else {
            $pingjia1 = $user['is_identity_authentication'] == 2 ? 1 : 0;
        }


        $pingjia2 = M('pingjia')->where(['user_id' => $user_id, 'to_user' => $to_user])->select();

        // $evaluate = M('dymanic_enroll')->where(['main_id'=>$user_id,'user_id'=>$main_id,'tryst'=>1,'evaluate'=>0])->select();

        if (!$pingjia1) {

            $result = ['code' => 220, 'msg' => '未获取联系方式'];

            $this->ajaxReturn($result);

        } else {

            if ($pingjia2) {

                $result = ['code' => 220, 'msg' => '已评价过'];

                $this->ajaxReturn($result);

            } else {

                $result = ['code' => 200, 'msg' => '操作成功'];

                $this->ajaxReturn($result);

            }

        }

    }

    //评价供选词列表
    public function evalist()
    {
        $main_id = I('main_id');  //被评价用户ID

        $user = M('user')->field('id, sex')->find($main_id);
        $types = $user['sex'] == '男' ? 1 : 2;

        $data = M('evaluate_default')->field('id, content')->where(['types' => $types])->select();

        $pingjia = M('pingjia')->field('id, content')->where(['to_user' => $main_id])->select();

        $nums = [];
        foreach ($pingjia as $item) {
            $content = json_decode($item['content'], true);

            foreach ($content as $n) {
                $nums[$n] = isset($nums[$n]) ? $nums[$n] + 1 : 1;
            }
        }

        foreach ($data as $key => $item) {
            $data[$key]['num'] = $nums[$item['id']] ?? 0;
        }

        $result = ['code' => 200, 'data' => $data, 'msg' => '操作成功'];

        $this->ajaxReturn($result);
    }

    //评价
    public function evaluate()
    {
        $to_user = $_REQUEST['main_id'];  //被评价用户ID
        $user_id = $_REQUEST['userid'];  //评价用户ID
        $content = $_REQUEST['evaluate']; //评价内容

        //$content = json_encode($content);

        if (!$content) {

            $result = ['code' => 220, 'msg' => '评价内容不能为空'];

            $this->ajaxReturn($result);

        }

        $result = M('pingjia')->data(['user_id' => $user_id, 'to_user' => $to_user, 'content' => $content])->add();

        $name = M('user')->where(['id' => $user_id])->getField('name');

        $context = ['name' => $name, 'content' => $content];

        $arr = [

            'to_user' => $to_user,

            'uid' => $user_id,

            'type' => 11,

            'context' => $context

        ];

        M('sys_message')->data($arr)->add();

        if ($result) {

            $result = ['code' => 200, 'msg' => '评价成功'];

            $this->ajaxReturn($result);

        } else {

            $result = ['code' => 220, 'msg' => '评价失败'];

            $this->ajaxReturn($result);

        }
    }

    //我的动态列表(发布的 + 报名的)
    public function selflist()
    {
        $page = $_REQUEST['page'];//页数
        $type = $_REQUEST['type'] ?: 0;

        $pagecount = $_REQUEST['pagecount'];//分页条数
        $userid = $_REQUEST['userid'];//用户id

        $where = "u.id = dy.userid and dy.dy_id = de.dy_id and dy.shenhe = 1 and dy.type = $type and de.user_id=" . $userid;
        $order = "dy.addtime desc";

        if ($page == null || $page <= 0) {
            $page = 0;
        }

        if ($pagecount == null || $pagecount <= 0) {
            $pagecount = 10;
        }

        $startcount = $page * $pagecount;

        $model = M();

        //查询点击赞和喜欢
        $thumbsup = $model->query("select dy_id from dymanic_userthumbsup where userid=$userid;");

        $lover = $model->query("select dy_id from dymanic_userlover where userid=$userid;");

        //查询动态列表
        $sql = "select dy.*,u.id,u.vip_end_datetime,u.head_100,u.head_300,u.nvshen,
                u.kejian,u.through_membership,u.name,u.age,u.sex,u.is_identity_authentication,u.constellation,u.vip_end_datetime,
                de.tryst from dymanic as dy,user as u,dymanic_enroll as de where $where ORDER BY $order limit $startcount,$pagecount;";

        $data = $model->query($sql);

        //发布的动态
        $where = " ";

        $where .= "u.id = dy.userid and dy.type = $type and dy.userid=" . $userid;

        $sql = "select dy.*,u.id,u.vip_end_datetime,u.head_100,u.head_300,u.nvshen,u.kejian,u.through_membership,u.name,
                u.age,u.sex,u.is_identity_authentication,u.attestation,u.constellation,u.vip_end_datetime,u.realname_auth,
                u.register_datetime from dymanic as dy,user as u where $where ORDER BY $order limit $startcount,$pagecount;";

        $data1 = $model->query($sql);

        if ($data1) {
            foreach ($data1 as $k => $v) {
                $tryst = M('dymanic_enroll')->where(['dy_id' => $v['dy_id']])->getfield('tryst');
                $data1[$k]['tryst'] = $tryst ?: 0;
            }
        }

        if ($data1) {
            foreach ($data1 as $v) {
                $data[] = $v;
            }
        }

        $num = [];
        foreach ($data as $v) {
            $num[] = M('dymanic_userthumbsup')->where(['dy_id' => $v['dy_id']])->count('userid');
        }

        //是否报名
        foreach ($data as $k => $v) {
            $enroll = M('dymanic_enroll')->where(['dy_id' => $v['dy_id'], 'user_id' => $userid])->find();

            $data[$k]['self_enroll'] = $enroll ? 1 : 0;

            $data[$k]['is_vip'] = time() < strtotime($v['vip_end_datetime']) ? 1 : 0;
        }

        //报名人数
        foreach ($data as $k => $v) {
            if ($v['enroll'] == NULL) {
                $data[$k]['enroll'] = 0;
            }
        }

        //判断是否当天发布的
        $start = strtotime(date("Y-m-d"), time());

        foreach ($data as $k => $v) {
            $data[$k]['is_new'] = (strtotime($v['register_datetime']) + 86400) > time() ? 1 : 0;
            $data[$k]['overdue'] = strtotime($v['addtime']) < $start ? 1 : 0;

            $data[$k]['overdue'] = $v['state'] ? 1 : 0;
        }

        //判断用户点赞
        if (is_array($thumbsup)) {

            $k = count($data, 0);

            for ($i = 0; $i < $k; $i++) {

                $kt = count($thumbsup, 0);

                $data[$i]['isthumbsup'] = 0;

                for ($j = 0; $j < $kt; $j++) {

                    if ($thumbsup[$j]['dy_id'] == $data[$i]['dy_id']) {

                        $data[$i]['isthumbsup'] = 1;//代表点赞

                    }
                }
            }

        } else {

            $j = count($data, 0);

            for ($i = 0; $i < $j; $i++) {

                $data[$i]['isthumbsup'] = 0;//代表无点赞

            }

        }

        //判断用户喜爱
        if (is_array($lover)) {

            $k = count($data, 0);

            for ($i = 0; $i < $k; $i++) {

                $kt = count($lover, 0);

                $data[$i]['islover'] = 0;

                for ($j = 0; $j < $kt; $j++) {

                    if ($lover[$j]['dy_id'] == $data[$i]['dy_id']) {

                        $data[$i]['islover'] = 1;//代表点赞

                    }
                }
            }

        } else {

            $j = count($data, 0);

            for ($i = 0; $i < $j; $i++) {

                $data[$i]['islover'] = 0;//代表无点赞

            }

        }

        //判断二维数组有多少个一维数组。
        $k = sizeof($data);

        for ($i = 0; $i < $k; $i++) {


            $data[$i]['num'] = $num[$i];

            $distance = $data[$i]['distance'];

            $data[$i]['distance'] = format_distance($distance);

            // $data[$i]['masterimg'] = explode(",",$data[$i]['masterimg']);//把多图片字符串转成数组。
            $data[$i]['masterimg'] = explode(",", $data[$i]['sumbImage']);
            $data[$i]['sumbImage'] = explode(",", $data[$i]['sumbImage']);//把多图片压缩字符串转成数组。

            $data[$i]['vip_end_datetime'] = strtotime($data[$i]['vip_end_datetime']) >= time() ? 1 : 0;//判断会员

            $data[$i]['through_membership'] = explode(" ", $data[$i]['through_membership'])[1];

        }

        //点赞人列表
        $zan = [];
        foreach ($data as $k => $v) {

            $zan = M('dymanic_userthumbsup')->alias("dy")//左表起别名

            ->join("LEFT JOIN user as u on dy.userid=u.id")//左链接

            ->field("u.id,u.head_portrait,u.head_300,u.head_100")//左表显示全部字段，右表显示部分字段

            ->where("dy.dy_id=" . $v['dy_id'])//条件

            ->order('dy.id desc')
                ->select();

            $data[$k]['zan'] = $zan;


            $comment = M('dycomment')->alias("dy")//左表起别名

            ->join("LEFT JOIN user as u on dy.userid=u.id")//左链接

            ->field("dy.content as text,u.id,u.name,u.head_portrait,u.head_300,u.head_100")//左表显示全部字段，右表显示部分字段

            ->where("dy.type=0 and dy.dy_id=" . $v['dy_id'])//条件

            ->order('dy.addtime desc')
                ->select();


            $data[$k]['text'] = $comment;


        }

        //排序。发布动态+报名动态。根据addtime
        $arr = array_column($data, 'addtime');

        array_multisort($arr, SORT_DESC, $data);

        $this->ajaxReturn(['code' => 200, 'result' => $data]);
    }

    //他人动态列表(发布的 + 报名的)
    public function otherlist()
    {
        $page = $_REQUEST['page'];//页数
        $type = $_REQUEST['type'] ?: 0;

        $pagecount = $_REQUEST['pagecount'];//分页条数

        $userid = $_REQUEST['userid'];//用户id

        $to_user = $_REQUEST['to_user'];//被查看用户id

        $where = " ";

        $where .= "u.id = dy.userid and dy.shenhe = 1 and dy.type = $type and dy.userid=" . $to_user;

        $order = " ";

        $order .= "dy.addtime desc";

        if ($page == null || $page <= 0) {
            $page = 0;
        }

        if ($pagecount == null || $pagecount <= 0) {
            $pagecount = 10;
        }

        $startcount = $page * $pagecount;

        $model = M();

        //查询点击赞和喜欢
        $thumbsup = $model->query("select dy_id from dymanic_userthumbsup where userid=$userid;");

        $lover = $model->query("select dy_id from dymanic_userlover where userid=$userid;");

        //查询动态列表
        $sql = "select dy.*, u.id,u.vip_end_datetime,u.head_100,u.head_300,u.nvshen,u.kejian,u.through_membership,
            u.name,u.age,u.sex,u.is_identity_authentication,u.attestation,u.constellation,u.vip_end_datetime,u.realname_auth,
            u.register_datetime, u.noble_grade, u.noble_time from dymanic as dy,user as u where $where ORDER BY $order limit $startcount,$pagecount;";

        $data = $model->query($sql);

        $num = [];
        foreach ($data as $v) {
            $num[] = M('dymanic_userthumbsup')->where(['dy_id' => $v['dy_id']])->count('userid');
        }

        //是否报名
        foreach ($data as $k => $v) {
            $enroll = M('dymanic_enroll')->where(['dy_id' => $v['dy_id'], 'user_id' => $userid])->find();

            if ($enroll) {
                $data[$k]['self_enroll'] = 1;
            } else {
                $data[$k]['self_enroll'] = 0;
            }

            if (time() < strtotime($v['vip_end_datetime'])) {
                $data[$k]['is_vip'] = time() < strtotime($v['vip_end_datetime']) ? 1 : 0;
            }
        }

        //报名人数
        foreach ($data as $k => $v) {
            if ($v['enroll'] == NULL) {
                $data[$k]['enroll'] = 0;
            }

            $data[$k]['is_new'] = (strtotime($v['register_datetime']) + 86400) > time() ? 1 : 0;
        }

        //判断用户点赞
        if (is_array($thumbsup)) {

            $k = count($data, 0);

            for ($i = 0; $i < $k; $i++) {

                $kt = count($thumbsup, 0);

                $data[$i]['isthumbsup'] = 0;

                for ($j = 0; $j < $kt; $j++) {
                    if ($thumbsup[$j]['dy_id'] == $data[$i]['dy_id']) {
                        $data[$i]['isthumbsup'] = 1;//代表点赞
                    }
                }
            }
        } else {
            $j = count($data, 0);
            for ($i = 0; $i < $j; $i++) {
                $data[$i]['isthumbsup'] = 0;//代表无点赞
            }
        }
        //判断用户喜爱
        if (is_array($lover)) {

            $k = count($data, 0);

            for ($i = 0; $i < $k; $i++) {
                $kt = count($lover, 0);

                $data[$i]['islover'] = 0;

                for ($j = 0; $j < $kt; $j++) {
                    if ($lover[$j]['dy_id'] == $data[$i]['dy_id']) {
                        $data[$i]['islover'] = 1;//代表点赞
                    }
                }
            }
        } else {
            $j = count($data, 0);

            for ($i = 0; $i < $j; $i++) {
                $data[$i]['islover'] = 0;//代表无点赞
            }
        }

        $ids = array_column($data, 'userid');
        $personals = M('config_personal')->where(['user_id' => ['in', $ids]])->getField('user_id, id, hide_distance');

        $config = M('config_system')->where(['category' => 'user'])->getField('title, content');
        $gradeNoble = M('grade_noble')->where(['id' => ['gt', 0]])->getField('grade, icon');
        $attentions = M('attention')->where(['user_id' => $userid, 'to_user' => $to_user, 'sys_channel' => 1])->find();

        $k = sizeof($data);

        for ($i = 0; $i < $k; $i++) {
            $data[$i]['num'] = $num[$i];

            $distance = $data[$i]['distance'];

            $data[$i]['distance'] = format_distance($distance);

            // $data[$i]['masterimg'] = explode(",",$data[$i]['masterimg']);//把多图片字符串转成数组。

            $data[$i]['masterimg'] = explode(",", $data[$i]['sumbImage']);
            $data[$i]['sumbImage'] = explode(",", $data[$i]['sumbImage']);//把多图片压缩字符串转成数组。

            $data[$i]['vip_end_datetime'] = strtotime($data[$i]['vip_end_datetime']) >= time() ? 1 : 0;//判断会员

            $data[$i]['through_membership'] = explode(" ", $data[$i]['through_membership'])[1];

            if (isset($personals[$data[$i]['userid']]['hide_distance']) && $personals[$data[$i]['userid']]['hide_distance']) {
                $data[$i]['citys'] = '';
            }

            if ($config['hide_city'] && $data[$i]['sex'] == '女') {
                $data[$i]['citys'] = '';
            }

            $data[$i]['is_following'] = $attentions ? 1 : 0;

            if ($data[$i]['noble_grade'] && $data[$i]['noble_time'] > time()) {
                $data[$i]['noble_icon'] = isset($gradeNoble[$data[$i]['noble_grade']]) ? changeUrl($gradeNoble[$data[$i]['noble_grade']]) : '';

                $data[$i]['is_vip'] = 1;
            } else {
                $data[$i]['is_vip'] = 0;
            }
        }

        $result = array("code" => 200, "result" => $data);

        $this->ajaxReturn($result);
    }

    //我的关注用户列表
    public function myattention()
    {
        $types = I('types') ?: 1;

        $user_id = $_REQUEST['user_id'];  //用户id

        $page = $_REQUEST['page'] ?: 1;
        $pagesize = $_REQUEST['pagesize'] ?: 10;
        $keyword = $_REQUEST['keyword'] ?: '';

        $num = ($page - 1) * $pagesize;
        $count = 0;
        if ($types == 1) {
            $ids = M('attention')->where(['user_id' => $user_id, 'sys_channel' => 1])->order('addtime desc')->limit($num, $pagesize)->getfield('to_user', true);
        } else if ($types == 2) {
            $ids = M('attention')->where(['to_user' => $user_id, 'sys_channel' => 1])->order('addtime desc')->limit($num, $pagesize)->getfield('user_id', true);
            $count = M('attention')->where(['to_user' => $user_id, 'sys_channel' => 1])->count();
        } else if ($types == 3) {
            $ids = M('attention')->where(['user_id' => $user_id, 'sys_channel' => 1])->getfield('to_user', true);

            $ids = M('attention')->where(['user_id' => ['in', $ids], 'to_user' => $user_id, 'sys_channel' => 1])->order('addtime desc')->limit($num, $pagesize)->getfield('user_id', true);
        } else {
            $ids = [];
            $contain = [];
            // $intimate = M()->Query("SELECT * from user_intimate where (FIND_IN_SET($user_id, couple_a) or FIND_IN_SET($user_id, couple_b)) and intimate >= 2 order by intimate desc limit $num, $pagesize");
            $intimate = M()->Query("(SELECT * from user_intimate where couple_a like '$user_id,%' and intimate >= 2 and unshow = 0) union (SELECT * from user_intimate where couple_b like '$user_id,%' and intimate >= 2 and unshow = 0) order by intimate desc limit $num, $pagesize");
            if ($intimate) {
                foreach ($intimate as $item) {
                    $couple = explode(',', $item['couple_a']);
                    if ($couple[0] != $user_id && !in_array($couple[0], $ids)) {
                        $ids[] = $couple[0];
                        $contain[$couple[0]] = $item['intimate'];
                    }
                    if ($couple[1] != $user_id && !in_array($couple[1], $ids)) {
                        $ids[] = $couple[1];
                        $contain[$couple[1]] = $item['intimate'];
                    }

                    $couple = explode(',', $item['couple_b']);
                    if ($couple[0] != $user_id && !in_array($couple[0], $ids)) {
                        $ids[] = $couple[0];
                        $contain[$couple[0]] = $item['intimate'];
                    }
                    if ($couple[1] != $user_id && !in_array($couple[1], $ids)) {
                        $ids[] = $couple[1];
                        $contain[$couple[1]] = $item['intimate'];
                    }
                }
            }
            $ids = array_unique($ids);
        }

        if ($keyword) {
            $nickname_ids = M('user')->where(['id'=>['in',$ids], 'name'=>['like', '%'.$keyword.'%']])->getField('id', true);
            $remark_ids_a = M('chat_charge_records')->where(['user_id'=>$user_id, 'another_id'=>['in', $ids], 'another_remark'=>['like', '%'.$keyword.'%']])->getField('another_id', true);
            $remark_ids_b = M('chat_charge_records')->where(['another_id'=>$user_id, 'user_id'=>['in', $ids], 'user_remark'=>['like', '%'.$keyword.'%']])->getField('user_id', true);
            $ids = array_unique(array_merge($nickname_ids?:[], $remark_ids_a?:[], $remark_ids_b?:[]));
        }

        $current_user = M()->table('user')->field('longitude,latitude,register_datetime')->where(['id' => $user_id])->find();
        $longitude = $current_user['longitude'];//经度
        $latitude = $current_user['latitude'];//纬度

        $order = 'field(id,"'.implode(',', $ids).'")';
        if ($types == 4) {
            $order = 'last_login_datetime desc';
        }

        $user = M()->table('user')->field("id,head_300,vip_end_datetime,nvshen,kejian,name,city,occupation,last_login_datetime,hide_distance,is_hide,constellation,sex,age,attestation,img_auth,hide_distance,xuni_discount,is_online,hide_online_time,role,real_avatar,entertainment,entertainment_child,
        ROUND(
                6378.138 * 2 * ASIN(
                    SQRT(
                        POW(
                            SIN(
                                (" . $latitude . " * PI() / 180 - latitude * PI() / 180) / 2
                            ), 2
                        ) + COS (" . $latitude . " * PI() / 180) * COS(latitude * PI() / 180) * POW(
                            SIN(
                                (" . $longitude . " * PI() / 180 - longitude * PI() / 180) / 2
                            ), 2
                        )
                    )
                ) * 1000
            ) AS distance
        ")->where(['id' => ['in', $ids], 'delete_time' => 0])->order($order)->select();

        if ($page == 0) {
            $user = null;
        }

        $config = M('config_system')->where(['title' => 'hide_city'])->getField('title, content');
        $gradeNoble = M('grade_noble')->where(['id' => ['gt', 0]])->getField('grade, icon');

        $data = [];
        
        if ($user) {
            $ids = array_column($user, 'id');
    
            $user_labels = D('Labels')->lists($ids);
            $timenow = time();
            $attention_ids = M('attention')->where(['user_id' => $user_id, 'sys_channel' => 1])->getfield('to_user', true);
        
            $datetime = date('Y-m-d H:i:s');
            $chat_discount_users = M('act_chat_discount_user')->where("state=0 and starttime <= '$datetime' and endtime >= '$datetime'")->getField('user_id,discount');

            foreach ($user as $k => $v) {
        
                $img_count = M('user_img')->where(['user_id' => $v['id']])->count();
        
                //上次登录时间
                if ($v['hide_online_time']) {
                    $time = '保密';
                } else {
                    $time = strtotime($v['last_login_datetime']);
                    if (!$time) {
                        $time = "未知";
                    }
            
                    $diff = $timenow - $time;
                    $time = $diff < 1800 ? '在线' : ($v['is_online'] ? (substr($v['id'], -1) + 1 + substr($timenow, -3, 1)).'分钟前在线' : '');

                    // if ($v['is_online']) {
                    //     $time = "在线";
                    // } else if ($diff < 60) {
                    //     $time = "刚刚";
                    // } else if ($diff < 3600) {
                    //     $time = floor($diff / 60) . "分钟前";
                    // } else if ($diff < 86400) {
                    //     $time = floor($diff / 3600) . "小时前";
                    // } else if ($diff < (86400 * 7)) {
                    //     $time = floor($diff / 86400) . "天前";
                    // } else if ($diff < (86400 * 30)) {
                    //     $time = floor($diff / 86400 / 7) . "周前";
                    // } else if ($diff < (86400 * 366)) {
                    //     $time = floor($diff / 86400 / 30) . "个月前";
                    // } else if ($diff < (86400 * 366 * 3)) {
                    //     $time = floor($diff / 86400 / 365) . "年前";
                    // } else {
                    //     $time = date("Y-m-d H:i:s", $time);
                    // }
                }
        
                // 虚拟距离
                $distance = $v['xuni_discount'] + 0 ? $v['xuni_discount'] : $v['distance'];
        
                //距离
                $distance = $v['hide_distance'] ? '保密' : ($distance >= 1000 ? number_format(($distance / 1000), 1) . 'km' : number_format($distance, 1) . 'm');
        
                if ($config['hide_city'] && $v['sex'] == '女') {
                    $city = '';
                } else {
                    $city = $v['city'];
                }
        
                if ($v['noble_grade'] && $v['noble_time'] > time()) {
                    $noble_icon = isset($gradeNoble[$v['noble_grade']]) ? changeUrl($gradeNoble[$v['noble_grade']]) : '';
            
                    $is_vip = 1;
                } else {
                    $is_vip = 0;
                }
    
                $labels = $user_labels[$v['id']] ?? [];
        
                $item = [
                    "user_head" => $v['head_300'],
                    "user_name" => $v['name'],
                    "city" => $city,
                    "occupation" => $v['occupation'],
                    "user_distance" => $distance,//距离
                    "user_id" => $v['id'],
                    "user_sex" => $v['sex'],
                    "user_age" => $v['age'],
                    "imgcount" => $img_count[0],
                    "attestation" => $v['attestation'],
                    "last_login_datetime" => $time,
                    "is_online" => $v['is_online'],
                    "img_auth" => $v['img_auth'],
                    "love" => 1,
                    'constellation' => $v['constellation'],
                    'sort' => array_search($v['id'], $ids),
                    'noble_icon' => $noble_icon,
                    'is_vip' => $is_vip,
                    'labels' => $labels,
                    'intimate' => 0,
                    'hide_distance' => $v['hide_distance'],
                    'is_hide' => $v['is_hide'],
                    "real_avatar" => $v['real_avatar'],
                    "entertainment" => $v['entertainment'],
                    "entertainment_child" => $v['entertainment_child'],
                ];


                $item['entertainment_text'] = M('user_entertainment')->where(['id'=>$item['entertainment'] + 1])->getField('name');
                if ($item['entertainment_child']) {
                    $additionValue = 1;
                    $numbersArray = explode(',', $item['entertainment_child']);
                    $resultArray = array_map(function ($number) use ($additionValue) {
                        return $number + $additionValue;
                    }, $numbersArray);
                    $resultString = implode(',', $resultArray);

                    $item['entertainment_child_text'] = M('user_entertainment')->where(['id'=>['in',$resultString]])->getField('name', true);
                    $item['entertainment_child_text'] = implode('|',$item['entertainment_child_text']);
                }

                if ($types == 4 && isset($contain[$item['user_id']]) && strtotime($current_user['register_datetime']) < strtotime('2012-09-22')) {
                    $item['intimate'] = $contain[$item['user_id']];
                }

                $uid_a = $user_id;
                $uid_b = $item['user_id'];
                $uid_remark_key = 'another_remark';
                if ($uid_a > $uid_b) {
                    $uid_a = $item['user_id'];
                    $uid_b = $user_id;
                    $uid_remark_key = 'user_remark';
                }
                $item['remark_name'] = M('chat_charge_records')->where(['user_id'=>$uid_a,'another_id'=>$uid_b])->getField($uid_remark_key);
                $item['is_attention'] = in_array($item['user_id'], $attention_ids);

                $item['is_chat_discount'] = false;
                if (isset($chat_discount_users[$item['user_id']])) {
                    $item['is_chat_discount'] = (floatval($chat_discount_users[$item['user_id']]) / 10) . '折';
                }


                $data[] = $item;
            }
        }
        
        if ($data) {
            $sort = array_column($data, 'sort');

            array_multisort($sort, SORT_ASC, $data);
        }

        $result = array("code" => 200, 'paging' => ['page' => $page, 'pagesize' => $pagesize, 'count'=>$count], "result" => $data);
        $this->ajaxReturn($result);
    }

    //取消约会广播
    public function deldymanic()
    {
        $dy_id = $_REQUEST['dy_id'];

        $type = M('dymanic')->where('dy_id=' . $dy_id)->getField('type');

        if ($type == '2') {
            $this->ajaxReturn(['code' => 220, 'msg' => '非约会广播，取消失败']);
        }

        $res = M('dymanic')->where('dy_id=' . $dy_id)->save(['state' => 1]);

        if ($res) {
            $this->ajaxReturn(['code' => 200, 'msg' => '约会广播已取消']);
        } else {
            $this->ajaxReturn(['code' => 220, 'msg' => '约会广播取消失败']);
        }
    }

    //浏览记录
    public function visit()
    {
        $user_id = I('user_id');  //用户id
        $types = I('types') ?: 2;

        $page = $_REQUEST['page'] ?: 1;
        $pagesize = $_REQUEST['pagesize'] ?: 10;
        $fans = $_REQUEST['fans'] ?? 0;

        if ($types == 1) { // 访客
            $field1 = 'user_id';
            $field2 = 'the_user';

            $user = M('user')->where(['id' => $user_id])->find();

            $ids = M('see_record')->where([$field1 => $user_id, 'is_read' => 0])->getField($field2, true);

            $avatars = [];
            if ($ids) {
                $data = M('user')->where(['id' => ['in', $ids]])->getField('head_100', true);

                for ($i = 0; $i < 3; $i++) {
                    if (isset($data[$i])) {
                        $avatars[] = changeUrl($data[$i]);
                    }
                }
            }

            // if ($user['noble_time'] < time() || !$user['noble_grade']) {
            //     exit(json_encode(['code' => 400, 'msg' => '开通会员查看', 'data' => ['count' => count($ids), 'avatars' => $avatars]]));
            // }

            // $privilege = M('grade_noble')->where(['grade' => $user['noble_grade']])->getField('privilege');
            // $privilege = explode(',', $privilege);

            // if (!in_array(5, $privilege)) {
            //     exit(json_encode(['code' => 400, 'msg' => '升级会员查看', 'data' => ['count' => count($ids), 'avatars' => $avatars]]));
            // }

            M('see_record')->where([$field1 => $user_id, 'is_read' => 0])->save(['is_read' => 1]);

        } else {    // 足迹
            $field1 = 'the_user';
            $field2 = 'user_id';
        }

        $num = ($page - 1) * $pagesize;

        $to_user = M('see_record')->where([$field1 => $user_id])->order('addtime desc')->limit($num, $pagesize)->getfield("id, $field2");
        if ($fans) {
            $fans_uids = M('attention')->where(['to_user'=>$user_id, 'sys_channel' => 1])->getField('user_id', true);
            $to_user = array_intersect($to_user, $fans_uids);
        }

        $current_user = M()->table('user')->field('longitude,latitude')->where(['id' => $user_id])->find();

        $longitude = $current_user['longitude'];//经度
        $latitude = $current_user['latitude'];//纬度

        $user = M()->table('user')
            ->field("id,head_300,vip_end_datetime,nvshen,kejian,name,city,occupation,last_login_datetime,constellation,
                sex,age,attestation,img_auth,hide_distance,xuni_discount,role,is_online,
            ROUND(
                6378.138 * 2 * ASIN(
                    SQRT(
                        POW(
                            SIN(
                                (" . $latitude . " * PI() / 180 - latitude * PI() / 180) / 2
                            ), 2
                        ) + COS (" . $latitude . " * PI() / 180) * COS(latitude * PI() / 180) * POW(
                            SIN(
                                (" . $longitude . " * PI() / 180 - longitude * PI() / 180) / 2
                            ), 2
                        )
                    )
                ) * 1000
            ) AS distance")
            ->where(['id' => ['in', $to_user], 'delete_time' => 0])->select();

        if ($page == 0) {
            $user = null;
        }

        $data = [];
        if ($user) {
            $ids = array_column($user, 'id');

            $user_labels = D('Labels')->lists($ids);

            foreach ($user as $v) {
                $img_count = M('user_img')->where(['user_id' => $v['id']])->count();

                $v['is_vip'] = time() < strtotime($v['vip_end_datetime']) ? 1 : 0;

                //上次登录时间
                if ($v['hide_online_time']) {
                    $time = '保密';
                } else {
                    $time = strtotime($v['last_login_datetime']);
                    if (!$time) {
                        $time = "未知";
                    }

                    $diff = time() - $time;
                    if ($v['is_online']) {
                        $time = "在线";
                    } else if ($diff < 60) {
                        $time = "刚刚";
                    } else if ($diff < 3600) {
                        $time = floor($diff / 60) . "分钟前";
                    } else if ($diff < 86400) {
                        $time = floor($diff / 3600) . "小时前";
                    } else if ($diff < (86400 * 7)) {
                        $time = floor($diff / 86400) . "天前";
                    } else if ($diff < (86400 * 30)) {
                        $time = floor($diff / 86400 / 7) . "周前";
                    } else if ($diff < (86400 * 366)) {
                        $time = floor($diff / 86400 / 30) . "个月前";
                    } else if ($diff < (86400 * 366 * 3)) {
                        $time = floor($diff / 86400 / 365) . "年前";
                    } else {
                        $time = date("Y-m-d H:i:s", $time);
                    }
                }

                // 虚拟距离
                $distance = $v['xuni_discount'] + 0 ? $v['xuni_discount'] : $v['distance'];

                //距离
                $distance = $v['hide_distance'] ? '保密' : ($distance >= 1000 ? number_format(($distance / 1000), 1) . 'km' : number_format($distance, 1) . 'm');

                $labels = $user_labels[$v['id']] ?? [];
                
                $v['city'] = $v['hide_distance'] ? '' : $v['city'];

                $item = [
                    "user_head" => $v['head_300'],
                    "user_name" => $v['name'],
                    "city" => $v['city'],
                    "occupation" => $v['occupation'],
                    "user_distance" => $distance,//距离
                    "user_id" => $v['id'],
                    "user_sex" => $v['sex'],
                    "user_age" => $v['age'],
                    "imgcount" => $img_count[0],
                    "is_vip" => $v['is_vip'],
                    "attestation" => $v['attestation'],
                    "last_login_datetime" => $time,
                    "is_online" => $v['is_online'],
                    "img_auth" => $v['img_auth'],
                    "love" => 1,
                    'constellation' => $v['constellation'],
                    'tags' => $v['tags'],
                    'top_grade' => $v['top_grade'],
                    'sort' => array_search($v['id'], $to_user),
                    'labels' => $labels
                ];
                $data[] = $item;
            }

            $sort = array_column($data, 'sort');

            array_multisort($sort, SORT_DESC, $data);
        }

        $result = array("code" => 200, 'paging' => ['page' => $page, 'pagesize' => $pagesize], "result" => $data);
        $this->ajaxReturn($result);
    }
}